package com.artron.mediaartron.ui.fragment.center;

import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.artron.baselib.base.BaseStaticFragment;
import com.artron.baselib.entity.Response;
import com.artron.baselib.image.ImageUtils;
import com.artron.baselib.utils.ToastUtil;
import com.artron.baselib.utils.UIUtils;
import com.artron.mediaartron.R;
import com.artron.mediaartron.data.config.Altar;
import com.artron.mediaartron.data.config.AppProfile;
import com.artron.mediaartron.data.entity.User;
import com.artron.mediaartron.data.net.RetrofitHelper;
import com.artron.mediaartron.data.net.api.LoginApi;
import com.artron.mediaartron.ui.activity.GeneralActivity;
import com.artron.mediaartron.util.RegexUtils;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import rx.functions.Action1;

/**
 * 绑定手机号
 * Created by qi on 2017/11/17.
 */

public class BindPhoneFragment extends BaseStaticFragment implements View.OnClickListener {

    @BindView(R.id.BindPhoneFragment_et_phone)
    protected EditText mEtPhone;
    @BindView(R.id.BindPhoneFragment_et_VerificationCode)
    protected EditText mEtVerificationCode;
    @BindView(R.id.BindPhoneFragment_et_newPwd)
    protected EditText mEtNewPwd;
    @BindView(R.id.BindPhoneFragment_iv_pwd_isVisibility)
    protected ImageView mIvPwdIsVisibility;
    @BindView(R.id.BindPhoneFragment_tv_sendVerificationCode)
    protected TextView mTvSendVerificationCode;
    @BindView(R.id.BindPhoneFragment_btn_complete)
    protected Button mBtnComplete;
    @BindView(R.id.BindPhoneFragment_iv_user_icon)
    protected ImageView mIvUserIcon;
    @BindView(R.id.BindPhoneFragment_tv_Phone)
    protected TextView mTvPhone;
    @BindView(R.id.BindPhoneFragment_ll_bindPhone)
    protected LinearLayout mLlBindPhone;
    @BindView(R.id.BindPhoneFragment_ll_not_bindPhone)
    protected LinearLayout mLlNotBindPhone;
    @BindView(R.id.BindPhoneFragment_btn_alteration_phone)
    protected Button mBtnAlterationPhone;
    @BindView(R.id.BindPhoneFragment_cb_treaty)
    protected CheckBox mCheckBox;
    @BindView(R.id.BindPhoneFragment_tv_treaty)
    protected TextView mTreaty;

    private int mCaptchaSecond = 0;
    private boolean isCanClickCaptcha = true;
    private boolean isShowPassword = true;
    private Timer mTimer;

    public static BindPhoneFragment newInstance() {
        Bundle args = new Bundle();
        BindPhoneFragment fragment = new BindPhoneFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_is_bind_phone;
    }

    @Override
    protected void initView() {
        User user = AppProfile.getUserInfo().getUser();
        if (!TextUtils.isEmpty(user.getLoginPlatform()) && TextUtils.isEmpty(user.getMobile())) {
            mLlNotBindPhone.setVisibility(View.VISIBLE);
            mLlBindPhone.setVisibility(View.GONE);
        } else {
            mLlBindPhone.setVisibility(View.VISIBLE);
            mLlNotBindPhone.setVisibility(View.GONE);
            setTelNum(user.getMobile());
        }
        ImageUtils.setCircleUrl(mIvUserIcon, user.getPhotoUrl());
        mTreaty.setOnClickListener(this);
        mBtnComplete.setOnClickListener(this);
        mIvPwdIsVisibility.setOnClickListener(this);
        mBtnAlterationPhone.setOnClickListener(this);
        mTvSendVerificationCode.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        String phoneNumber = mEtPhone.getText().toString().trim();
        String verificationCode = mEtVerificationCode.getText().toString().trim();
        String newPassword = mEtNewPwd.getText().toString().trim();
        switch (view.getId()) {
            case R.id.BindPhoneFragment_btn_complete://绑定完成
                bindPhoneComplete(phoneNumber, verificationCode, newPassword);
                break;
            case R.id.BindPhoneFragment_iv_pwd_isVisibility://新密码可见状态
                if (isShowPassword) {
                    mEtNewPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    mIvPwdIsVisibility.setImageResource(R.drawable.ic_password_visible);
                } else {
                    mEtNewPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    mIvPwdIsVisibility.setImageResource(R.drawable.ic_password_not_visible);
                }
                isShowPassword = !isShowPassword;
                mEtNewPwd.postInvalidate();
                break;
            case R.id.BindPhoneFragment_tv_sendVerificationCode://发送验证码
                sendVerificationCode(phoneNumber);
                break;
            case R.id.BindPhoneFragment_btn_alteration_phone://变更手机号
                GeneralActivity.startForResult(mContext, GeneralActivity.ALTERATION_PHONE, "更换手机号");
                break;
            case R.id.BindPhoneFragment_tv_treaty:
                GeneralActivity.start(mContext, GeneralActivity.HELP, "传给雅昌注册协议",
                        "http://pms.artup.com/pms/help/protocol.html");
                break;
        }

    }

    private void sendVerificationCode(String mobile) {
        if (regexPhone(mobile) && isCanClickCaptcha) {
            LoginApi loginApi = RetrofitHelper.getLoginApi();
            RetrofitHelper.subscript(loginApi.getCaptcha(mobile), new Action1<Response>() {
                @Override
                public void call(Response response) {
                    if ("OK".equals(response.getStatus())) {
                        UIUtils.showSnackbar(getView(), response.getMessage());
                        startCaptcha();
                    } else {
                        UIUtils.showSnackbar(getView(), "发送验证码失败，请检查网络");
                    }
                }
            });
        }
    }

    private void startCaptcha() {
        mCaptchaSecond = 60;
        isCanClickCaptcha = false;
        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mCaptchaSecond--;
                        if (mCaptchaSecond == 0) {
                            mTvSendVerificationCode.setText("重新发送");
                            isCanClickCaptcha = true;
                            mTimer.cancel();
                        } else {
                            mTvSendVerificationCode.setText(mCaptchaSecond + "s，重新发送");
                        }
                    }
                });
            }
        }, 1000, 1000);
    }

    /**
     * 绑定完成按钮的操作
     */
    private void bindPhoneComplete(final String phoneNumber, String verificationCode, String newPassword) {
        boolean checked = mCheckBox.isChecked();

        if (checked) {

            if (isNull(phoneNumber, "手机号码不能为空") && regexPhone(phoneNumber) &&
                    isNull(verificationCode, "验证码不能为空") && isNull(newPassword, "新密码不能为空")) {
                LoginApi loginApi = RetrofitHelper.getLoginApi();

                RetrofitHelper.subscript(loginApi.bindMobile(AppProfile.getUserInfo().getUser().getUtoken(),
                        phoneNumber, verificationCode, newPassword), new Action1<Response>() {
                    @Override
                    public void call(Response response) {
                        if ("OK".equals(response.getStatus())) {
//                        ToastUtil.show(response.getMessage());
                            mLlBindPhone.setVisibility(View.VISIBLE);
                            mLlNotBindPhone.setVisibility(View.GONE);
                            Altar userInfo = AppProfile.getUserInfo();
                            userInfo.getUser().setMobile(phoneNumber);
                            userInfo.update();
                            mTvPhone.setText("手机号码：" + phoneNumber);
                            if (mTimer != null) {
                                mTimer.cancel();
                            }
                        } else {
                            ToastUtil.show(response.getMessage());
                        }
                    }
                });
            }
        } else {
            ToastUtil.show("请选择同意并接受注册协议");
        }

    }

    /**
     * 判断字符串是否未null
     *
     * @param str
     * @param msg
     * @return
     */
    private boolean isNull(String str, String msg) {
        if (!TextUtils.isEmpty(str)) {
            return true;
        } else {
            ToastUtil.show(msg);
            return false;
        }
    }

    private boolean regexPhone(String s) {
        if (RegexUtils.isTelPhoneNum(s)) {
            return RegexUtils.isTelPhoneNum(s);
        } else {
            ToastUtil.show("手机号码格式不正确");
            return false;
        }
    }

    @Override
    public void onDestroy() {
        if (mTimer != null) {
            mTimer.cancel();
        }
        super.onDestroy();

    }


    public void setTelNum(String telNum) {
        if (!TextUtils.isEmpty(telNum)) {
            mTvPhone.setText("手机号码：" + getShowTelNum(telNum));
        }
    }

    private String getShowTelNum(String telNum) {
        String head = telNum.substring(0, 3);
        String tail = telNum.substring(telNum.length() - 4);
        return "手机号码：" + head + "****" + tail;
    }
}
